package  
{
	import flash.display.BitmapData;
	import flash.filters.BlurFilter;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import org.flixel.*;
	/**
	 * ...
	 * @author morgan
	 */
	public class BlurText extends FlxText
	{
		[Embed(source = "../data/georgia.ttf", fontFamily = "georgia", embedAsCFF = "false")] private var fnt_main:Class;
		
		public var clearWords:int = 0;
		public var nextWordInterp:Number = 0;
		public var clearingToWord:int = 0;
		
		public var wordPositions:Array = [];
		public function BlurText(x:int, y:int, size:int = 40) 
		{
			super(x, y, 640, "", true);
			setFormat("georgia", size, 0xffffffff, "left");
		}
		
		override public function update():void 
		{
			super.update();
			if (clearWords < clearingToWord)
			{
				nextWordInterp += FlxG.elapsed * 3;
				if (nextWordInterp > 1)
				{
					clearWords += 1 ;
					nextWordInterp = 0;
				}
			}
			calcFrame();
		}
		
		public function setText(txt:String):void
		{
			wordPositions.length = 0;
			wordPositions.push(0);
			text = "";
			var words:Array = txt.split(" ");
			for (var i:int = 0; i < words.length; i++)
			{
				text += words[i] + " ";
				wordPositions.push(_textField.getLineMetrics(0).width);
				FlxG.log(_textField.getLineMetrics(0).width);
			}
		}
		
		override public function draw():void 
		{
			if (clearWords + 1 < wordPositions.length)
			{
				var blur2:Number = size / 4 + 2;
				var blur1:Number = (1 - nextWordInterp) * blur2;
				var offset:Number = 3;
				var x1:int = wordPositions[clearWords];
				var x2:int = wordPositions[clearWords + 1];
				var rnd:Number = (Math.random() - 0.5) * size / 8;
				var nextBlur:BitmapData = new BitmapData(x2 - x1 + offset*2, height);
				nextBlur.applyFilter(framePixels, new Rectangle(x1 - offset, 0, x2 - x1 + offset*2, height), new Point(0, 0), new BlurFilter(blur1, blur1, 3));			
				FlxG.camera.buffer.draw(nextBlur, new Matrix(1, 0, 0, 1, x + x1 - offset, y + rnd));
				var endBlur:BitmapData = new BitmapData(width - x2 + offset*2, height);
				endBlur.applyFilter(framePixels, new Rectangle(x2 - offset, 0, width - x2 + offset*2, height), new Point(0, 0), new BlurFilter(blur2, blur2, 3));
				FlxG.camera.buffer.draw(endBlur, new Matrix(1, 0, 0, 1, x + x2 - offset, y + rnd));
				framePixels.fillRect(new Rectangle(x1, 0, width - x1, height), 0x00000000);
			}
			super.draw();
		}
		
	}

}